package com.qishenyuan.competition.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

public class PageUtil {

    public static IPage toIPage(PageQuery pageQuery) {
        Page page = new Page(pageQuery.getPageNumber(), pageQuery.getPageSize());
        return page;
    }

    public static <R> PageResult<R> toPageResult(IPage<R> iPage) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setList(iPage.getRecords());
        pageResult.setPageNumber((int) iPage.getCurrent());
        pageResult.setPageSize((int) iPage.getSize());
        pageResult.setTotalCount(iPage.getTotal());
        pageResult.setTotalPage(iPage.getPages());
        return pageResult;
    }


    public static <T> List<T> startPage(List<T> list, Integer pageNum,
                                        Integer pageSize) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        //记录总数
        Integer count = list.size();
        //页数
        Integer pageCount;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        //开始索引
        int fromIndex;

        //结束索引
        int toIndex;

        if (pageNum > pageCount) {
            return new ArrayList<>();
        }
        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        return list.subList(fromIndex, toIndex);
    }

}

